/*
Copyright © 2025 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"common-cobra/pak"
	"database/sql"
	"fmt"
	"strconv"
	"strings"

	"github.com/c-bata/go-prompt"
	"github.com/spf13/cobra"
)

var db *sql.DB

func Executor(input string) {

	input = strings.TrimSpace(input)
	if input == "" {
		return
	}
	// 执行 SQL 并输出结果
	rows, err := db.Query(input)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		return
	}
	defer rows.Close()

	// 解析列名
	cols, _ := rows.Columns()
	headers := strings.Join(cols, " | ")
	fmt.Printf("| %s |\n", headers)

	// 解析数据行
	for rows.Next() {
		values := make([]interface{}, len(cols))
		ptrs := make([]interface{}, len(cols))
		for i := range values {
			ptrs[i] = &values[i]
		}

		_ = rows.Scan(ptrs...)
		rowStr := make([]string, len(cols))
		for i, v := range values {
			rowStr[i] = fmt.Sprintf("%s", v)
		}
		fmt.Printf("| %s |\n", strings.Join(rowStr, " | "))
	}
}

// mysqlCmd represents the mysql command
var mysqlCmd = &cobra.Command{
	Use:   "mysql",
	Short: "command for mysql conn",
	Long:  `mysql数据库连接工具，按照顺序传递 host  port  user  pass  dbname  5个参数，可连接数据库执行sql命令`,
	Args:  cobra.ExactArgs(5),
	Run: func(cmd *cobra.Command, args []string) {
		// 参数顺序 host port  username password dbname
		port, err := strconv.Atoi(args[1])
		if err != nil {
			fmt.Println("端口格式错误!")
			return
		}
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", args[2], args[3], args[0], port, args[4])
		db, err = sql.Open("mysql", dsn)
		if err != nil {
			panic(err)
		}
		defer db.Close()
		db.SetMaxOpenConns(1) // 交互式场景通常单连接

		// 启动交互终端
		p := prompt.New(
			Executor,
			pak.Completer,
			prompt.OptionPrefix("mysql> "),
		)
		p.Run()
	},
}

func init() {
	rootCmd.AddCommand(mysqlCmd)
}
